﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using OBUCare.Core.DataAccess;
using OBUCare.Core.Models;
using OBUCare.Web.Infrastructure;
using OBUCare.Core.Common;
using OBUCare.Core.BL;

namespace OBUCare.Web.Areas.Admin.Controllers
{
    public class PartsSpecController : Controller
    {

        OBU_CAREContext db = new OBU_CAREContext();
        OBUCareOrderMgr obuMrg = new OBUCareOrderMgr();

        #region 显示型号配置主表
       
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 获取元器件型号配置主窗口信息
        /// </summary>
        /// <param name="supplier"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public IList<PARTS_SPECS> getPartsSpecs(int supplier, int status, int partsType)
        {
            Func<PARTS_SPECS, bool> fun = item => 
            {
                bool r = true;
                if (supplier != UIConstants.AllItemsValue)
                    r = item.SUPPLIER_ID == supplier;
                if (r && status != UIConstants.AllItemsValue)
                    r = item.STATUS == status;
                if (partsType != UIConstants.AllItemsValue)
                    r = item.PARTS_ID == partsType;
                return r;
            };
            var allItems = db.PARTS_SPECS.ToList();
            var result = (from i in allItems
                         where fun(i)
                         select i).OrderBy(r=>r.STATUS).OrderBy(r=>r.SUPPLIER_ID).OrderByDescending(r=>r.SPEC_NAME);

            return result.ToList();
        }

        [GridAction]
        public ActionResult List(int supplier, int status, int partsType)
        {
            var result = getPartsSpecs(supplier, status, partsType);
            var temp = new GridModel(result);
            return View(temp);
        }

        public ActionResult AddSpec(int? id )
        {
            return View();
        }

        [HttpPost]
        public ActionResult ConfirmAddSpec(string strIDs, string supplier, int? specID, string specName, string PartType)
        {
            bool success = false;
            string message = null;

            try
            {
                IList<long> idList=new List<long>();
                if(!strIDs.IsNullOrEmpty())
                    idList = strIDs.Split(',').ConvertTo(s => s.ToLong().Value);

                //var u = UIUtility.GetCurrentUser();

                //如果specID为空，则说明是新建spec
                //新建spec时，判断specName是否已存在
                if (!specID.HasValue)
                {
                    if (!checkSpecNameExit(specName,null))
                    {
                        return Json(new { success = false, message = "该标签型号名称已存在，不允许重复添加" }); 
                    }
                    PARTS_SPECS spec = new PARTS_SPECS();
                    spec.SPEC_NAME = specName;
                    spec.STATUS = DictTypeStatus.Normal.ToInt().Value;
                    spec.PARTS_ID = Convert.ToInt16(PartType);
                    var r = db.PARTS_TYPE.Find(spec.PARTS_ID);
                    spec.PARTS_NAME = r.PARTS_NAME;

                    if (idList.Count > 0)
                    {
                        var cInfo = db.View_Contract_Details.Find(idList[0]);
                        spec.SUPPLIER_ID = cInfo.SUPPLIER_ID;
                        spec.SUPPLIER_NAME = cInfo.SUPPLIER_Name;
                    }
                    else
                    {
                        var sInfo =db.SUPPLIERS.Find(supplier.ToInt().Value);
                        spec.SUPPLIER_ID = sInfo.ID;
                        spec.SUPPLIER_NAME = sInfo.SHORTNAME;                        
                    }

                    db.PARTS_SPECS.Add(spec);
                    db.SaveChanges();
                    specID = spec.ID;
                }

                
                idList.Each(id =>
                    {
                        var info = new PARTS_SPECS_DETAIL();
                        var cInfo = db.View_Contract_Details.Find(id);
                        info.CONTRACT_DETAIL_ID = cInfo.ID;
                        info.END_NO = cInfo.END_NO;
                        info.PARTS_SPEC_ID = specID.Value;
                        info.START_NO = cInfo.START_NO;
                        info.STATUS = DictTypeStatus.Normal.ToInt().Value;

                        db.PARTS_SPECS_DETAIL.Add(info);
                    });

                db.SaveChanges();

                success = true;
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }

            return Json(new { success = success, message = message });
        }

        [GridAction]
        public ActionResult SaveSpec(int ID, int Qsupplier, int Qstatus, string SPEC_NAME, int QpartsType)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var r = (from s in db.PARTS_STOCK
                             where s.PARTS_SPEC_ID == ID && s.TransferID==null && s.In_Stock_ID==null
                             select s).FirstOrDefault();
                    if (r != null)
                    {
                        Response.StatusCode = 500;
                        // Response.AppendHeader("message", Server.UrlEncode("该型号已引用，不允许编辑"));
                        //// throw new Exception("此型号已经入过库，不允许编辑");
                    }
                    else
                    {
                        var spec = db.PARTS_SPECS.Single(c => c.ID == ID);
                        if (spec.STATUS == (int)DictTypeStatus.NotUsed)
                        {
                            Response.StatusCode = 501;
                            //Response.AppendHeader("message", Server.UrlEncode("该型号已作废，不允许编辑"));
                        }
                        if (!checkSpecNameExit(SPEC_NAME, ID))
                        {
                            Response.StatusCode = 502;
                            // Response.AppendHeader("message", "该型号名称已存在，不允许重复");
                            //Response.HeaderEncoding = System.Text.Encoding.UTF8;
                            //Response.AppendHeader("message",  "该型号名称已存在，不允许重复");

                        }
                        else
                        {
                            UpdateModel(spec);
                            db.SaveChanges();
                        }
                    }
                }
                catch (Exception e)
                {
                    Response.StatusCode = 500;
                    Response.AppendHeader("message", Server.HtmlEncode("修改型号配置出现错误:"+e.Message));
                }
            }

            return View(new GridModel(getPartsSpecs(Qsupplier,Qstatus,QpartsType)));
        }


        [GridAction]
        public ActionResult DeleteSpec(int ID, int Qsupplier, int Qstatus, int QpartsType)
        {
            try
            {
                obuMrg.DeletePartSpec(ID);
            }
            catch (System.Exception e)
            {
                Response.StatusCode = 503;
                Response.AppendHeader("message", "删除型号配置出错: " + e.Message);
            }

            return View(new GridModel(getPartsSpecs(Qsupplier, Qstatus, QpartsType)));
        }

        #endregion

        #region 型号配置子表

        private IList<PARTS_SPECS_DETAIL> getPartsSpecDetails(int specID)
        {
            int status = DictTypeStatus.Deleted.ToInt().Value ;
            var result = from d in db.PARTS_SPECS_DETAIL
                         where d.PARTS_SPEC_ID == specID && d.STATUS !=status 
                         select d;
            return result.ToList();
        }

        [GridAction]
        public ActionResult ListDetails(int masterID)
        {
            var temp = new GridModel(getPartsSpecDetails(masterID));
            return View(temp);
        }

        /// <summary>
        /// 更新号段
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [GridAction]
        public JsonResult UpdateDetails(int id)
        {
            try
            {
                var item = db.PARTS_SPECS_DETAIL.Find(id);
                var contract = db.View_Contract_Details_ALL.Find(item.CONTRACT_DETAIL_ID);
                item.START_NO = contract.START_NO;
                item.END_NO = contract.END_NO;
                db.SaveChanges();
                return Json(new { success = true, message = "" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false , message = ex.Message });
            }       
        }

        [GridAction]
        public ActionResult DeleteSpecDetails(int masterID, int detailID)
        {
            try
            {
                var item = db.PARTS_SPECS_DETAIL.Find(detailID);
                item.STATUS = DictTypeStatus.Deleted.ToInt().Value;
                db.SaveChanges();
            }
            catch (System.Exception e)
            {
                Response.StatusCode = 500;
                Response.AppendHeader("message", "删除型号配置号断出错: " + e.Message);
            }

            return View(new GridModel(getPartsSpecDetails(masterID)));
        }
  
        #endregion


        #region Ajax DropDwonList DataSource

        /// <summary>
        /// 获取下拉列表的配件型号数据
        /// </summary>
        /// <returns></returns>
        public JsonResult GetDDLPartsSpecs(int id)
        {
            using(ObuDropDownListHlper ddlHelper = new ObuDropDownListHlper())
            {
                var selectItems = ddlHelper.GetPartsSpecs(null,id, true, new KeyValuePair<string, string>(UIConstants.Customize, UIConstants.Customize));
                
                return Json(selectItems, JsonRequestBehavior.AllowGet);
            }
        }        

        #endregion


        /// <summary>
        /// 获取合同信息
        /// </summary>
        /// <param name="supplier"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult ListContracts(int supplier)
        {
            var temp = new GridModel(getContracts(supplier));
            return View(temp);
        }

        private IList<View_Contract_Details> getContracts(int supplier)
        {
            IEnumerable<View_Contract_Details> r = null;
            if (supplier == UIConstants.AllItemsValue)
                r = db.View_Contract_Details;
            else
                r = from c in db.View_Contract_Details
                    where c.SUPPLIER_ID == supplier
                    select c;
            return r.ToList();
        }
        ///// <summary>
        ///// 判断新建时，型号名称是否已存在
        ///// </summary>
        ///// <param name="specName"></param>
        ///// <returns></returns>
        //public bool checkSpecNameExit(string specName)
        //{
        //    var spec = (from i in db.PARTS_SPECS.ToList()
        //                where i.SPEC_NAME==specName
        //                select i).ToList();
        //    if (spec != null && spec.Count() > 0)
        //    {
        //        return false;
        //    }
        //    return true;
        //}
        /// <summary>
        /// 判断新建或修改时，型号名称是否已存在
        /// </summary>
        /// <param name="specName"></param>
        /// <returns></returns>
        public bool checkSpecNameExit(string specName,int? specID)
        {
            PARTS_SPECS spec=null;
            if(specID.HasValue)
                spec = (from i in db.PARTS_SPECS
                        where i.SPEC_NAME == specName && i.ID!=specID.Value
                        select i).FirstOrDefault();
            else
                spec = (from i in db.PARTS_SPECS
                        where i.SPEC_NAME == specName 
                        select i).FirstOrDefault();            

            if (spec != null)
            {
                return false;
            }
            return true;
        }
        [HttpPost]
        public JsonResult GetPartsTypeBySpec(int specName)
        {
            try
            {
                var r = (from i in db.PARTS_SPECS.ToList()
                         where i.ID == specName
                         select i).ToList();
                var v = Json(new { success = true, message = "获取元器件名称" });
                if (r != null && r.Count() > 0)
                {
                   v= Json(new { success = true, partsType=r.FirstOrDefault().PARTS_ID});
                }
                return v;
            }
            catch (Exception)
            {

                return Json(new { success = false, message="获取元器件名称失败"});
            }
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
